package wxk.interview.serializable;

import java.io.ObjectStreamException;
import java.io.Serializable;

/**
 *
 * singleton 的对象如何解决序列化问题
 * @author wangxuekai
 * @version 2.2
 * @Date 2017/3/9.
 * @since 2.2
 */
public class PersonSingle implements Serializable {
    private static final long serialVersionUID = -49620164569133803L;

    private String name;
    private Integer idNo;


    private PersonSingle(){}

    private static PersonSingle single;

    // 汉式
    static {
        single = new PersonSingle("hua",12);
    }

    private PersonSingle(String name, Integer idNo) {
        this.name = name;
        this.idNo = idNo;
    }

    /*实现单利的另一种方式，懒汉式 内部类*/
//    private static class InstanceHolder{
//        static final PersonSingle instance = new PersonSingle("hua",12);
//    }

    public static PersonSingle getInstance(){
        return single;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getIdNo() {
        return idNo;
    }

    public void setIdNo(Integer idNo) {
        this.idNo = idNo;
    }

    private Object readResolve() throws ObjectStreamException{
        return single;
    }

    @Override
    public String toString() {
        return "PersonSingle{" +
                "name='" + name + '\'' +
                ", idNo=" + idNo +
                '}';
    }
}
